<script setup lang="ts">
import { computed, ref, watch } from 'vue'

// 商品基础信息
const goodsInfo = ref({
  id: '001',
  name: 'iPhone 15 Pro Max',
  description: '全新iPhone 15 Pro Max，搭载A17 Pro芯片，钛金属设计，专业级摄像系统',
  defaultPrice: 9999,
  originalPrice: 10999,
  images: [
    'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-1a_CN.jpg',
    'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-2_CN.jpg',
    'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-3a_CN.jpg',
  ],
})

// SKU 规格配置
const skuSpecs = ref([
  {
    name: '颜色',
    key: 'color',
    list: [
      { name: '原色钛金属', value: 'natural', image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-1a_CN.jpg' },
      { name: '蓝色钛金属', value: 'blue', image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-bluetitanium-pdp-image-position-1a_CN.jpg' },
      { name: '白色钛金属', value: 'white', image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-whitetitanium-pdp-image-position-1a_CN.jpg' },
      { name: '黑色钛金属', value: 'black', image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-blacktitanium-pdp-image-position-1a_CN.jpg' },
    ],
  },
  {
    name: '容量',
    key: 'storage',
    list: [
      { name: '256GB', value: '256gb' },
      { name: '512GB', value: '512gb' },
      { name: '1TB', value: '1tb' },
    ],
  },
  {
    name: '版本',
    key: 'version',
    list: [
      { name: '国行版', value: 'cn' },
      { name: '港版', value: 'hk' },
    ],
  },
])

// SKU 列表配置
const skuList = ref([
  // 原色钛金属
  { id: '001-natural-256gb-cn', color: 'natural', storage: '256gb', version: 'cn', price: 9999, stock: 50, image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-1a_CN.jpg' },
  { id: '002-natural-512gb-cn', color: 'natural', storage: '512gb', version: 'cn', price: 11499, stock: 30, image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-1a_CN.jpg' },
  { id: '003-natural-1tb-cn', color: 'natural', storage: '1tb', version: 'cn', price: 13499, stock: 20, image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-1a_CN.jpg' },
  { id: '004-natural-256gb-hk', color: 'natural', storage: '256gb', version: 'hk', price: 9299, stock: 25, image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-1a_CN.jpg' },

  // 蓝色钛金属
  { id: '005-blue-256gb-cn', color: 'blue', storage: '256gb', version: 'cn', price: 9999, stock: 45, image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-bluetitanium-pdp-image-position-1a_CN.jpg' },
  { id: '006-blue-512gb-cn', color: 'blue', storage: '512gb', version: 'cn', price: 11499, stock: 35, image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-bluetitanium-pdp-image-position-1a_CN.jpg' },
  { id: '007-blue-1tb-cn', color: 'blue', storage: '1tb', version: 'cn', price: 13499, stock: 15, image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-bluetitanium-pdp-image-position-1a_CN.jpg' },

  // 白色钛金属
  { id: '008-white-256gb-cn', color: 'white', storage: '256gb', version: 'cn', price: 9999, stock: 40, image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-whitetitanium-pdp-image-position-1a_CN.jpg' },
  { id: '009-white-512gb-cn', color: 'white', storage: '512gb', version: 'cn', price: 11499, stock: 28, image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-whitetitanium-pdp-image-position-1a_CN.jpg' },

  // 黑色钛金属
  { id: '010-black-256gb-cn', color: 'black', storage: '256gb', version: 'cn', price: 9999, stock: 55, image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-blacktitanium-pdp-image-position-1a_CN.jpg' },
  { id: '011-black-512gb-cn', color: 'black', storage: '512gb', version: 'cn', price: 11499, stock: 42, image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-blacktitanium-pdp-image-position-1a_CN.jpg' },
  { id: '012-black-1tb-cn', color: 'black', storage: '1tb', version: 'cn', price: 13499, stock: 18, image: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-blacktitanium-pdp-image-position-1a_CN.jpg' },
])

// 当前选中的规格
const selectedSpecs = ref<Record<string, string>>({
  color: 'natural',
  storage: '256gb',
  version: 'cn',
})

// 购买数量
const quantity = ref(1)

// 是否显示规格选择弹窗
const showSkuPopup = ref(false)

// 当前选中的SKU
const currentSku = computed(() => {
  return skuList.value.find(sku =>
    sku.color === selectedSpecs.value.color
    && sku.storage === selectedSpecs.value.storage
    && sku.version === selectedSpecs.value.version,
  )
})

// 当前价格
const currentPrice = computed(() => {
  return currentSku.value?.price || goodsInfo.value.defaultPrice
})

// 当前库存
const currentStock = computed(() => {
  return currentSku.value?.stock || 0
})

// 当前商品图片
const currentImages = computed(() => {
  const selectedColor = skuSpecs.value[0].list.find(item => item.value === selectedSpecs.value.color)
  if (selectedColor?.image) {
    return [selectedColor.image, ...goodsInfo.value.images.slice(1)]
  }
  return goodsInfo.value.images
})

// 规格选择处理
function handleSpecSelect(specKey: string, specValue: string) {
  selectedSpecs.value[specKey] = specValue
}

// 数量变化处理
function handleQuantityChange(value: number) {
  quantity.value = Math.max(1, Math.min(value, currentStock.value))
}

// 立即购买
function handleBuyNow() {
  if (currentStock.value === 0) {
    uni.showToast({ title: '商品已售罄', icon: 'none' })
    return
  }

  uni.showToast({
    title: `购买 ${quantity.value} 件，总价 ¥${(currentPrice.value * quantity.value).toLocaleString()}`,
    icon: 'none',
    duration: 2000,
  })
}

// 加入购物车
function handleAddToCart() {
  if (currentStock.value === 0) {
    uni.showToast({ title: '商品已售罄', icon: 'none' })
    return
  }

  uni.showToast({
    title: '已加入购物车',
    icon: 'success',
  })
}

// 显示规格选择弹窗
function showSpecSelector() {
  showSkuPopup.value = true
}

// 监听规格变化，更新图片
watch(() => selectedSpecs.value.color, () => {
  // 颜色变化时可以添加额外逻辑
})
</script>

<template>
  <view class="goods-detail">
    <!-- 商品图片轮播 -->
    <view class="goods-images">
      <wd-swiper
        :list="currentImages"
        :autoplay="false"
        :indicator-dots="true"
        height="375px"
        border-radius="0"
      >
        <template #default="{ item }">
          <image
            :src="item"
            mode="aspectFit"
            class="swiper-image"
          />
        </template>
      </wd-swiper>
    </view>

    <!-- 商品基本信息 -->
    <view class="goods-info">
      <view class="price-section">
        <view class="current-price">
          ¥{{ currentPrice.toLocaleString() }}
        </view>
        <view class="original-price">
          ¥{{ goodsInfo.originalPrice.toLocaleString() }}
        </view>
        <view class="stock-info">
          库存{{ currentStock }}件
        </view>
      </view>

      <view class="goods-title">
        {{ goodsInfo.name }}
      </view>
      <view class="goods-desc">
        {{ goodsInfo.description }}
      </view>

      <!-- 已选规格显示 -->
      <view class="selected-specs" @click="showSpecSelector">
        <view class="specs-label">
          已选
        </view>
        <view class="specs-value">
          <text v-for="(spec, key) in selectedSpecs" :key="key">
            {{ skuSpecs.find(s => s.key === key)?.list.find(item => item.value === spec)?.name }}
            {{ key !== Object.keys(selectedSpecs)[Object.keys(selectedSpecs).length - 1] ? '，' : '' }}
          </text>
        </view>
        <wd-icon name="arrow-right" size="16px" color="#999" />
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="action-buttons">
        <wd-button
          type="warning"
          size="large"
          :disabled="currentStock === 0"
          @click="handleAddToCart"
        >
          加入购物车
        </wd-button>
        <wd-button
          type="error"
          size="large"
          :disabled="currentStock === 0"
          @click="handleBuyNow"
        >
          立即购买
        </wd-button>
      </view>
    </view>

    <!-- SKU规格选择弹窗 -->
    <wd-popup
      v-model="showSkuPopup"
      position="bottom"
      :safe-area-inset-bottom="true"
      border-radius="20px 20px 0 0"
    >
      <view class="sku-popup">
        <!-- 弹窗头部 -->
        <view class="popup-header">
          <view class="popup-title">
            选择规格
          </view>
          <wd-icon
            name="close"
            size="20px"
            @click="showSkuPopup = false"
          />
        </view>

        <!-- 商品信息 -->
        <view class="popup-goods-info">
          <image
            :src="currentSku?.image || currentImages[0]"
            class="popup-goods-image"
          />
          <view class="popup-goods-detail">
            <view class="popup-price">
              ¥{{ currentPrice.toLocaleString() }}
            </view>
            <view class="popup-stock">
              库存{{ currentStock }}件
            </view>
            <view class="popup-selected">
              已选：
              <text v-for="(spec, key) in selectedSpecs" :key="key">
                {{ skuSpecs.find(s => s.key === key)?.list.find(item => item.value === spec)?.name }}
                {{ key !== Object.keys(selectedSpecs)[Object.keys(selectedSpecs).length - 1] ? '，' : '' }}
              </text>
            </view>
          </view>
        </view>

        <!-- 规格选择 -->
        <view class="spec-sections">
          <view
            v-for="spec in skuSpecs"
            :key="spec.key"
            class="spec-section"
          >
            <view class="spec-title">
              {{ spec.name }}
            </view>
            <view class="spec-options">
              <view
                v-for="option in spec.list"
                :key="option.value"
                class="spec-option"
                :class="{
                  'spec-option-active': selectedSpecs[spec.key] === option.value,
                  'spec-option-disabled': !skuList.some(sku =>
                    sku[spec.key] === option.value
                    && Object.keys(selectedSpecs).every(key =>
                      key === spec.key || sku[key] === selectedSpecs[key],
                    ) && sku.stock > 0,
                  ),
                }"
                @click="handleSpecSelect(spec.key, option.value)"
              >
                {{ option.name }}
              </view>
            </view>
          </view>
        </view>

        <!-- 数量选择 -->
        <view class="quantity-section">
          <view class="quantity-title">
            数量
          </view>
          <wd-input-number
            v-model="quantity"
            :min="1"
            :max="currentStock"
            :disabled="currentStock === 0"
            @change="handleQuantityChange"
          />
        </view>

        <!-- 弹窗底部按钮 -->
        <view class="popup-actions">
          <wd-button
            type="warning"
            size="large"
            block
            :disabled="currentStock === 0"
            @click="handleAddToCart"
          >
            加入购物车
          </wd-button>
          <wd-button
            type="error"
            size="large"
            block
            :disabled="currentStock === 0"
            @click="handleBuyNow"
          >
            立即购买
          </wd-button>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<style lang="scss" scoped>
.goods-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120px;
}

.goods-images {
  background: white;

  .swiper-image {
    width: 100%;
    height: 100%;
  }
}

.goods-info {
  background: white;
  padding: 20px;
  margin-top: 10px;

  .price-section {
    display: flex;
    align-items: baseline;
    margin-bottom: 15px;

    .current-price {
      font-size: 28px;
      font-weight: bold;
      color: #ff4142;
      margin-right: 10px;
    }

    .original-price {
      font-size: 14px;
      color: #999;
      text-decoration: line-through;
      margin-right: 15px;
    }

    .stock-info {
      font-size: 12px;
      color: #666;
      margin-left: auto;
    }
  }

  .goods-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    margin-bottom: 8px;
    line-height: 1.4;
  }

  .goods-desc {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
    margin-bottom: 20px;
  }

  .selected-specs {
    display: flex;
    align-items: center;
    padding: 15px 0;
    border-top: 1px solid #f0f0f0;

    .specs-label {
      font-size: 14px;
      color: #333;
      margin-right: 10px;
    }

    .specs-value {
      flex: 1;
      font-size: 14px;
      color: #666;
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 15px 20px;
  padding-bottom: calc(15px + env(safe-area-inset-bottom));
  border-top: 1px solid #f0f0f0;

  .action-buttons {
    display: flex;
    gap: 15px;

    :deep(.wd-button) {
      flex: 1;
    }
  }
}

.sku-popup {
  background: white;
  max-height: 80vh;
  overflow-y: auto;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;

    .popup-title {
      font-size: 18px;
      font-weight: bold;
      color: #333;
    }
  }

  .popup-goods-info {
    display: flex;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;

    .popup-goods-image {
      width: 80px;
      height: 80px;
      border-radius: 8px;
      margin-right: 15px;
    }

    .popup-goods-detail {
      flex: 1;

      .popup-price {
        font-size: 20px;
        font-weight: bold;
        color: #ff4142;
        margin-bottom: 5px;
      }

      .popup-stock {
        font-size: 12px;
        color: #666;
        margin-bottom: 8px;
      }

      .popup-selected {
        font-size: 12px;
        color: #999;
      }
    }
  }

  .spec-sections {
    padding: 0 20px;

    .spec-section {
      padding: 20px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .spec-title {
        font-size: 16px;
        font-weight: bold;
        color: #333;
        margin-bottom: 15px;
      }

      .spec-options {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;

        .spec-option {
          padding: 8px 16px;
          border: 1px solid #e0e0e0;
          border-radius: 6px;
          font-size: 14px;
          color: #333;
          background: white;
          transition: all 0.3s;

          &.spec-option-active {
            border-color: #ff4142;
            color: #ff4142;
            background: #fff5f5;
          }

          &.spec-option-disabled {
            color: #ccc;
            background: #f5f5f5;
            border-color: #f0f0f0;
          }
        }
      }
    }
  }

  .quantity-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;

    .quantity-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
  }

  .popup-actions {
    padding: 20px;
    display: flex;
    gap: 15px;

    :deep(.wd-button) {
      flex: 1;
    }
  }
}
</style>

<route lang="json">
{
  "name": "goodsDetail",
  "style": {
    "navigationBarTitleText": "商品详情"
  }
}
</route>
